import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const channelStore = createSlice({
  name: "channel",
  initialState: {
    img: null,
  },

  reducers: {
    setImg(store, action) {
      store.img = action.payload;
    },
  },
});

/**
 * Redux的异步操作
 * 1、配置一个同步方法
 * 2、单独封装一个函数、在函数中 return 一个新函数、在新函数中
 *    2.1 封装异步请求数据
 *    2.2 调用同步actionCreater方法传入数据
 * 3、组件中的dispatch方法保持不变
 */

const { setImg } = channelStore.actions;
const channelReducer = channelStore.reducer;


function AsyncGetImg() {
  return async (dispatch) => {
    let res = await axios.get("https://yesno.wtf/api");
    console.log(res);
    dispatch(setImg(res.data.image));
  };
}

export { AsyncGetImg };

export default channelReducer;
